package com.vichat.common.util;

import org.apache.commons.lang3.StringUtils;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

/**
 * SELECT UNIX_TIMESTAMP('2037-12-31 23:59:59');
 * SELECT FROM_UNIXTIME(2145887999)
 */

/**
 * <p>
 * Description:
 * </p>
 * <p>
 * 日期时间公共方法类
 * </p>
 * <p>
 * 该类提供了日期格式,处理等功能。
 * </p>
 * <p>
 * Copyright: Copyright (c) 2006
 * </p>
 */
public class DateUtil {

    public static final long ONE_DAY = 24L * 60 * 60 * 1000;
    public static final long DAYS_30 = 30L * 24 * 60 * 60 * 1000;

    public static Timestamp getTimestatmpByDate(Date datetime) {
        return new Timestamp(datetime.getTime());
    }

    public static Timestamp getTimestatmpByTime(Long datetime) {
        return new Timestamp(datetime);
    }

    /**
     * @return Integer
     * @Description:当前系统时间(/1000)
     */
    public static Integer CalendarCurrentTimeOld() {
        return new Long(Calendar.getInstance().getTimeInMillis() / 1000).intValue();
    }

    /**
     * @return Long
     * @Description:日历模式的当前时间(/1000)
     */
    public static long getCalendarCurrentTimeInMillisOld() {
        return Calendar.getInstance().getTimeInMillis() / 1000;
    }

    /**
     * @return Long
     * @Description:日历模式的当前时间
     */
    public static long getCalendarCurrentTimeInMillis() {
        return Calendar.getInstance().getTimeInMillis();
    }

    public static Timestamp getCalendarCurrentTimestamp() {
        return new Timestamp(Calendar.getInstance().getTimeInMillis());
    }

    /**
     * @return long
     * @Description:当前系统Mysql最大失效时间
     */
    public static long getMySqlMaxExpireTimeLong() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 2099);
        calendar.set(Calendar.MONTH, 11);
        calendar.set(Calendar.DAY_OF_MONTH, 31);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return new Long(calendar.getTimeInMillis());
    }

    /**
     * @return
     */
    public static Timestamp getMySqlMaxExpireTime() {
        return new Timestamp(getMySqlMaxExpireTimeLong());
    }

    /**
     * @return String 格式化的日期字符串
     * @Description:得到当前日期，格式yyyy-MM-dd。 @ FrameWork使用
     */
    public static String getFormattedDateYYYYMMDD() {
        return getFormattedDate(getDateByString(""));
    }

    /**
     * 对输入的日期按照默认的格式yyyy-MM-dd转换. FrameWork使用
     *
     * @param dtDate java.sql.Timestamp 需要进行格式化的日期字符串
     * @return String 经过格式化后的字符串
     */
    public static String getFormattedDate(Date dtDate) {
        return getFormattedDate(dtDate, "yyyy-MM-dd");
    }

    public static String getFormattedDateUrl(Date dtDate) {
        if(dtDate == null){
            dtDate=new Date();
        }
        String formatStr = "yyyy/MM/dd/";
        SimpleDateFormat formatter = new SimpleDateFormat(formatStr);

        return formatter.format(dtDate);
    }

    /**
     * 对输入的日期按照默认的格式yyyy-MM-dd转换. FrameWork使用
     *
     * @param iTime java.sql.Timestamp 需要进行格式化的日期字符串
     * @return String 经过格式化后的字符串
     */
    public static String getFormattedDate(long iTime) {
        String formatStr = "yyyy-MM-dd";
        SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
        Date tdate = new Date(iTime);
        return formatter.format(tdate);
    }

    /**
     * 对输入的日期按照默认的格式yyyy-MM-dd转换. FrameWork使用
     *
     * @param iTime java.sql.Timestamp 需要进行格式化的日期字符串
     * @return String 经过格式化后的字符串
     */
    public static String getLongFormattedDate(long iTime) {
        String formatStr = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
        Date tdate = new Date(iTime * 1000);
        return formatter.format(tdate);
    }

    /**
     * @return String 格式化的日期字符串
     * @Description:得到当前日期，格式yyyy-MM-dd HH:mm:ss
     */
    public static String getFormattedDateYYYYMMDDHHMMSS() {
        return getFormattedDateTime(getDateByString(""));
    }

    /**
     * 对输入的日期按照默认的格式yyyy-MM-dd转换. FrameWork使用
     *
     * @param dtDate java.sql.Timestamp 需要进行格式化的日期字符串
     * @return String 经过格式化后的字符串
     */
    public static String getFormattedDateTime(Date dtDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dtDate);
        return getFormattedDate(new Timestamp(calendar.getTimeInMillis()), "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 得到当前日期时间,格式为yyyy-MM-dd hh:mm:ss. FrameWork使用
     *
     * @return String
     */
    public static String getCurrDateTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Timestamp(
                getCalendarCurrentTimeInMillis()));
    }

    /**
     * 对输入的日期字符串进行格式化, 如果输入的是0000/00/00 00:00:00则返回空串. FrameWork使用
     *
     * @param strDate     String 需要进行格式化的日期字符串
     * @param strFormatTo String 要转换的日期格式
     * @return String 经过格式化后的字符串
     */
    public static String getFormattedDate(String strDate, String strFormatTo) {
        if ((strDate == null) || strDate.trim().equals("")) {
            return "";
        }
        strDate = strDate.replace('/', '-');
        strFormatTo = strFormatTo.replace('/', '-');
        if (strDate.equals("0000-00-00 00:00:00") || strDate.equals("1800-01-01 00:00:00")) {
            return "";
        }
        String formatStr = strFormatTo; // "yyyyMMdd";
        if ((strDate == null) || strDate.trim().equals("")) {
            return "";
        }
        switch (strDate.trim().length()) {
            case 6:
                if (strDate.substring(0, 1).equals("0")) {
                    formatStr = "yyMMdd";
                } else {
                    formatStr = "yyyyMM";
                }
                break;
            case 8:
                formatStr = "yyyyMMdd";
                break;
            case 10:
                if (strDate.indexOf("-") == -1) {
                    formatStr = "yyyy/MM/dd";
                } else {
                    formatStr = "yyyy-MM-dd";
                }
                break;
            case 11:
                if (strDate.getBytes().length == 14) {
                    formatStr = "yyyy年MM月dd日";
                } else {
                    return "";
                }
            case 14:
                formatStr = "yyyyMMddHHmmss";
                break;
            case 19:
                if (strDate.indexOf("-") == -1) {
                    formatStr = "yyyy/MM/dd HH:mm:ss";
                } else {
                    formatStr = "yyyy-MM-dd HH:mm:ss";
                }
                break;
            case 21:
                if (strDate.indexOf("-") == -1) {
                    formatStr = "yyyy/MM/dd HH:mm:ss.S";
                } else {
                    formatStr = "yyyy-MM-dd HH:mm:ss.S";
                }
                break;
            default:
                return strDate.trim();
        }
        try {
            SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(formatter.parse(strDate));
            formatter = new SimpleDateFormat(strFormatTo);
            return formatter.format(calendar.getTime());
        } catch (Exception e) {
            // Common.printLog("转换日期字符串格式时出错;" + e.getMessage());
            return "";
        }
    }

    /**
     * 根据传入的日期字符串转换成相应的日期对象， 如果字符串为空或不符合日期格式，则返回当前时间。 FrameWork使用
     *
     * @param strDate String 日期字符串
     * @return java.sql.Timestamp 日期对象
     */
    public static Timestamp getDateByString(String strDate) {
        if (strDate.trim().equals("")) {
            return new Timestamp(System.currentTimeMillis());
        }
        try {
            strDate = getFormattedDate(strDate, "yyyy-MM-dd HH:mm:ss");
            return Timestamp.valueOf(strDate);
        } catch (Exception ex) {
            // logger.error(ex.getMessage());
            return null;
        }
    }

    public static Timestamp getDateByString(String strDate, String strFormat) {
        if (StringUtils.isBlank(strDate)) {
            return new Timestamp(System.currentTimeMillis());
        }
        try {
            SimpleDateFormat formatter = new SimpleDateFormat(strFormat);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(formatter.parse(strDate));
            return new Timestamp(calendar.getTimeInMillis());
        } catch (Exception ex) {
            // logger.error(ex.getMessage());
            return null;
        }
    }

    /**
     * 对输入的日期进行格式化, 如果输入的日期是null则返回空串. FrameWork使用
     *
     * @param dtDate      java.sql.Timestamp 需要进行格式化的日期字符串
     * @param strFormatTo String 要转换的日期格式
     * @return String 经过格式化后的字符串
     */
    public static String getFormattedDate(Date dtDate, String strFormatTo) {
        if (dtDate == null) {
            return "";
        }
        if (dtDate.equals(new Timestamp(0))) {
            return "";
        }
        strFormatTo = strFormatTo.replace('/', '-');
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
            if (Integer.parseInt(formatter.format(dtDate)) < 1900) {
                return "";
            } else {
                formatter = new SimpleDateFormat(strFormatTo);
                return formatter.format(dtDate);
            }
        } catch (Exception e) {
            // logger.error("转换日期字符串格式时出错;" + e.getMessage());
            return "";
        }
    }

    /**
     * 计算两个日期之间相差的天数
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate,Date bdate) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        smdate=sdf.parse(sdf.format(smdate));
        bdate=sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 返回两个日期之间隔了多少天
     *
     * @param date1
     * @param date2
     * @throws ParseException
     */
    public static int DateDiff(String date1, String date2) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        Date d1 = sdf.parse(date1);
        Date d2 = sdf.parse(date2);
        int i = (int) ((d2.getTime() - d1.getTime()) / (3600 * 24 * 1000));
        return i;
    }

    /**
     * 返回两个日期之间隔了多少小时
     *
     */
    public static String TimeDiff(String pBeginTime, String pEndTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh");
        Long beginL = format.parse(pBeginTime).getTime();
        Long endL = format.parse(pEndTime).getTime();
        Long hour = ((endL - beginL)) / 3600000;
        return hour.toString();
    }

    /**
     * 返回两个日期之间隔了多少分钟
     */
    public static long getDiffMinutes(String str1, String str2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return min;
    }

    public static long getDiffMinutes(Date one, Date two) {

        long min = 0;
        try {
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            min = diff / (60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return min;
    }
    /**
     * 返回日期与系统日期之间隔了多少秒
     * @param date
     * @return
     */
    public static long getDiffSecond(Date date) {
        long a = new Date().getTime();
        long b = date.getTime();
        long c = ((a - b) / 1000);
        return c;
    }

    /**
     * 判断两个时间是否同一天
     * @param date1
     * @param date2
     * @return
     */
    public static boolean isSameDate(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        boolean isSameYear = cal1.get(Calendar.YEAR) == cal2
                .get(Calendar.YEAR);
        boolean isSameMonth = isSameYear
                && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
        boolean isSameDate = isSameMonth
                && cal1.get(Calendar.DAY_OF_MONTH) == cal2
                .get(Calendar.DAY_OF_MONTH);
        return isSameDate;
    }

    public static boolean dateDiff(String startTime, String endTime, String format, String str) {
        boolean flag = false;
        SimpleDateFormat sd = new SimpleDateFormat(format);
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        long diff;
        long day = 0;
        long hour = 0;
        long min = 0;
        try {
            diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
            day = diff / nd;
            hour = diff % nd / nh + day * 24;
            min = diff % nd % nh / nm + day * 24 * 60;
            if (day > 0) {
                flag = true;
                return flag;
            } else if (hour > 0) {
                flag = true;
                return flag;
            } else if (min > 30) {
                flag = true;
                return flag;
            } else {
                flag = true;
                return flag;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 返回两个日期之间隔了几个月
     *
     */
    public static int betweenMonthByTime(long begin, long end) throws Exception {
        return betweenMonthByTime(new Timestamp(begin), new Timestamp(end));
    }

    /**
     * 返回两个日期之间隔了几个月
     *
     */
    public static int betweenMonthByTime(Date begin, Date end) throws Exception {
        Calendar cbegin = Calendar.getInstance();
            cbegin.setTime(begin);
            int byear = cbegin.get(Calendar.YEAR);
            int bmonth = cbegin.get(Calendar.MONTH);
            int bday = cbegin.get(Calendar.DAY_OF_MONTH);

            Calendar cend = Calendar.getInstance();
            cend.setTime(end);
            int eyear = cend.get(Calendar.YEAR);
            int emonth = cend.get(Calendar.MONTH);
            int eday = cend.get(Calendar.DAY_OF_MONTH);

            int add = 0;
            if (eday > bday && eday - bday >= 15) {
                add = 1;
            } else if (eday < bday && bday - eday > 15) {
            add = -1;
        }

        return (eyear - byear) * 12 + (emonth - bmonth) + add;
    }

    /**
     * 返回两个日期之间隔了几个月
     *
     */
    public static int betweenMonthByNature(Date begin, Date end) throws Exception {
        Calendar cbegin = Calendar.getInstance();
        cbegin.setTime(begin);
        int byear = cbegin.get(Calendar.YEAR);
        int bmonth = cbegin.get(Calendar.MONTH);
        int bday = cbegin.get(Calendar.DAY_OF_MONTH);

        Calendar cend = Calendar.getInstance();
        cend.setTime(end);
        int eyear = cend.get(Calendar.YEAR);
        int emonth = cend.get(Calendar.MONTH);
        int eday = cend.get(Calendar.DAY_OF_MONTH);


        return (eyear - byear) * 12 + (emonth - bmonth) + (eday > bday ? 1 : 0);
    }

    // public static Timestamp DateAddMonth(Timestamp timest1,int month)
    // {
    // timest1.setMonth(timest1.getMonth() + month);
    // return timest1;
    // }

    /**
     * 得到当前日期，格式yyyy年MM月dd日。
     *
     * @param strDate    String
     * @param bNextMonth boolean
     * @return String
     */
    public static String getCNToday(String strDate, boolean bNextMonth) {
        String strToday = strDate;
        int iYear = Integer.parseInt(strToday.substring(0, 4));
        int iMonth = Integer.parseInt(strToday.substring(5, 7));
        int iDay = Integer.parseInt(strToday.substring(8, 10));
        if (!bNextMonth) {
            return iYear + "年" + iMonth + "月" + iDay + "日";
        } else {
            if (iMonth < 12) {
                iMonth++;
                return iYear + "年" + iMonth + "月1日";
            } else {
                iYear++;
                return iYear + "年1月1日";

            }

        }
    }

    /**
     * 得到今天日期，格式yyyy-MM-dd。
     *
     * @return String 格式化的日期字符串
     */
    public static String getToday(String format) {
        Date cDate = new Date();
        if (format == null || "".equals(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat(format);
        return cSimpleDateFormat.format(cDate);
    }

    /**
     * 得到昨天日期，格式yyyy-MM-dd。
     *
     * @return String 格式化的日期字符串
     */
    public static String getYesterday(String format) {
        Date cDate = new Date();
        cDate.setTime(cDate.getTime() - 24 * 3600 * 1000);
        if (format == null || "".equals(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat(format);
        return cSimpleDateFormat.format(cDate);
    }

    /**
     * 得到前天日期，格式yyyy-MM-dd。
     *
     * @return String 格式化的日期字符串
     */
    public static String getBeforeYesterday(String format) {
        Date cDate = new Date();
        cDate.setTime(cDate.getTime() - 48 * 3600 * 1000);
        if (format == null || "".equals(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat(format);
        return cSimpleDateFormat.format(cDate);
    }

    /**
     * 得到明天日期，格式yyyy-MM-dd。
     *
     * @return String 格式化的日期字符串
     */
    public static String getTomorrow(String format) {
        Date cDate = new Date();
        cDate.setTime(cDate.getTime() + 24 * 3600 * 1000);
        if (format == null || "".equals(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat(format);
        return cSimpleDateFormat.format(cDate);
    }

    public static String getAfterTomorrow(String format) {
        Date cDate = new Date();
        cDate.setTime(cDate.getTime() + 48 * 3600 * 1000);
        if (format == null || "".equals(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat(format);
        return cSimpleDateFormat.format(cDate);
    }

    public static Timestamp getTodayTime(String format) {
        Date cDate = new Date();
        if (format == null || "".equals(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat(format);
        return getDateByString(cSimpleDateFormat.format(cDate));
        // return Timestamp.valueOf(cSimpleDateFormat.format(cDate));
    }

    /**
     * 得到昨天日期，格式yyyy-MM-dd。
     *
     * @return String 格式化的日期字符串
     */
    public static Timestamp getYesterdayTIme(String format) {
        Date cDate = new Date();
        cDate.setTime(cDate.getTime() - 24 * 3600 * 1000);
        if (format == null || "".equals(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat(format);
        return getDateByString(cSimpleDateFormat.format(cDate));
        // return Timestamp.valueOf(cSimpleDateFormat.format(cDate));
    }

    /**
     * 得到明天日期，格式yyyy-MM-dd。
     *
     * @return String 格式化的日期字符串
     */
    public static Timestamp getTomorrowTime(String format) {
        Date cDate = new Date();
        cDate.setTime(cDate.getTime() + 24 * 3600 * 1000);
        if (format == null || "".equals(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat(format);
        return getDateByString(cSimpleDateFormat.format(cDate));
        // return Timestamp.valueOf(cSimpleDateFormat.format(cDate));
    }

    public static Timestamp getAfterTomorrowTime(String format) {
        Date cDate = new Date();
        cDate.setTime(cDate.getTime() + 48 * 3600 * 1000);
        if (format == null || "".equals(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat(format);
        return getDateByString(cSimpleDateFormat.format(cDate));
        // return Timestamp.valueOf(cSimpleDateFormat.format(cDate));
    }

    public static Timestamp getWeekTime(String format) {
        Date cDate = new Date();
        cDate.setTime(cDate.getTime() + 7 * 24 * 3600 * 1000);
        if (format == null || "".equals(format)) {
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat(format);
        return getDateByString(cSimpleDateFormat.format(cDate));
        // return Timestamp.valueOf(cSimpleDateFormat.format(cDate));
    }

    /**
     * 得到指定的日期，如一年三个月零九天后(以yyyy/MM/dd格式显示)参数为("yyyy/MM/dd",1,3,9)
     *
     * @param strFormat
     * @param iYear
     * @param iMonth
     * @param iDate
     * @return
     */
    public static String getSpecTime(String strFormat, int iYear, int iMonth, int iDate, int iHour,
                                     int iMinute, int iSecond) {
        Calendar rightNow = Calendar.getInstance();
        rightNow.set(Calendar.YEAR, rightNow.get(Calendar.YEAR) + iYear);
        rightNow.set(Calendar.MONTH, rightNow.get(Calendar.MONTH) + iMonth);
        rightNow.set(Calendar.DATE, rightNow.get(Calendar.DATE) + iDate);
        rightNow.set(Calendar.HOUR, rightNow.get(Calendar.HOUR) + iHour);
        rightNow.set(Calendar.MINUTE, rightNow.get(Calendar.MINUTE) + iMinute);
        rightNow.set(Calendar.SECOND, rightNow.get(Calendar.SECOND) + iSecond);
        SimpleDateFormat df = new SimpleDateFormat(strFormat);
        return df.format(rightNow.getTime());
    }

    /**
     * 得到当前日期格式yyyyMM转换。
     *
     * @return String 经过格式化后的字符串
     */
    public static String getCurrentYearMonth() {
        return getYearMonth(new Timestamp(System.currentTimeMillis()));
    }

    /**
     * 对输入的日期进行默认的格式yyyyMM转换。
     * @return String 经过格式化后的字符串
     */
    public static String getYearMonth(Date dtDate) {
        return getFormattedDate(dtDate, "yyyyMM");
    }

    public static String getYearMonthDay(Date dtDate) {
        return getFormattedDate(dtDate, "yyyyMMdd");
    }

    /**
     * 对输入的日期进行默认的格式yyyyMM转换。
     *
     * @return String 经过格式化后的字符串
     */
    public static long getLongDay(Timestamp dtDate) {
        String strDay = getFormattedDate(dtDate, "yyyyMMdd");
        long iDay = Long.parseLong(strDay);
        return iDay;
    }

    public static long getDay(Timestamp dtDate) {
        String strDay = getFormattedDate(dtDate, "dd");
        long iDay = Long.parseLong(strDay);
        return iDay;
    }

    /**
     * @return
     */
    public static long getForeverTimeLong() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 2099);
        calendar.set(Calendar.MONTH, 11);
        calendar.set(Calendar.DAY_OF_MONTH, 31);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTimeInMillis();
    }

    /**
     * @return
     */
    public static Timestamp getForeverTime() {
        return new Timestamp(getForeverTimeLong());
    }

    public static long getCurrMilSec() {

        return (new Date()).getTime();
    }

    /**
     * 得到当前日期，格式yyyy-MM-dd。 FrameWork使用
     *
     * @return String 格式化的日期字符串
     */
    public static String getCurrDate() {
        return getFormattedDate(getDateByString(""));
    }

    public static Long getCurrTime() {
        return Calendar.getInstance().getTimeInMillis() / 1000;
    }

    public static final int getYear(Timestamp time) {
        GregorianCalendar cal = _genCalendar(time);
        return cal.get(GregorianCalendar.YEAR);
    }

    /**
     * @param time
     * @param aYears
     * @return
     */
    public static final Timestamp addYear(Timestamp time, int aYears) {
        GregorianCalendar cal = _genCalendar(time);
        cal.add(GregorianCalendar.YEAR, aYears);
        return new Timestamp(cal.getTimeInMillis());
    }

    /**
     * @param time
     * @param aMonth
     * @return
     */
    public static final Timestamp addMonth(Date time, int aMonth) {
        GregorianCalendar cal = _genCalendar(time);
        cal.add(GregorianCalendar.MONTH, aMonth);
        return new Timestamp(cal.getTimeInMillis());
    }

    /**
     * @param time
     * @return
     */
    public static int getMonth(Timestamp time) {
        GregorianCalendar cal = _genCalendar(time);
        return cal.get(GregorianCalendar.MONTH);
    }

    /**
     * @param time
     * @return
     * @throws Exception
     */
    public static int getWeek(Timestamp time) {
        GregorianCalendar cal = _genCalendar(time);
        return cal.get(GregorianCalendar.WEEK_OF_YEAR) - 1;
    }

    /**
     * @param time
     * @param aDays
     * @return
     */
    public static final Timestamp addDay(Timestamp time, int aDays) {
        GregorianCalendar cal = _genCalendar(time);
        cal.add(GregorianCalendar.DAY_OF_MONTH, aDays);
        return new Timestamp(cal.getTimeInMillis());
    }

    /**
     * @param time
     * @return
     */
    public static int _getDay(Timestamp time) {
        GregorianCalendar cal = _genCalendar(time);
        return cal.get(GregorianCalendar.DAY_OF_MONTH);
    }

    /**
     * 加一天
     * @param n
     * @return
     */
    public static String addDay(String s, int n) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cd = Calendar.getInstance();
            cd.setTime(sdf.parse(s));
            cd.add(Calendar.DATE, n);//增加一天
            return sdf.format(cd.getTime());
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @param time
     * @param aHours
     * @return
     */
    public static final Timestamp addHour(Timestamp time, int aHours) {
        GregorianCalendar cal = _genCalendar(time);
        cal.add(GregorianCalendar.HOUR, aHours);
        return new Timestamp(cal.getTimeInMillis());
    }

    /**
     * @param date
     * @param aHours
     * @return
     */
    public static final String addHour(Date date, int aHours) {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        GregorianCalendar cal = _genCalendar(date);
        cal.setTime(date);
        cal.add(GregorianCalendar.HOUR, aHours);
        return sdf.format(cal.getTime());
    }
    
    public static final String addHour(Date date, Double aHours) {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        GregorianCalendar cal = _genCalendar(date);
        cal.setTime(date);
        cal.add(GregorianCalendar.MINUTE, new Double(aHours * 60).intValue());
        return sdf.format(cal.getTime());
    }
    /**
     * @param time
     * @param aMinutes
     * @return
     */
    public static final Timestamp addMinutes(Timestamp time, int aMinutes) {
        GregorianCalendar cal = _genCalendar(time);
        cal.add(GregorianCalendar.MINUTE, aMinutes);
        return new Timestamp(cal.getTime().getTime());
    }

    /**
     * @param time
     * @param aSeconds
     * @return
     */
    public static final Timestamp addSecond(Timestamp time, int aSeconds) {
        GregorianCalendar cal = _genCalendar(time);
        cal.add(GregorianCalendar.SECOND, aSeconds);
        return new Timestamp(cal.getTime().getTime());
    }

    public static GregorianCalendar _genCalendar(Date time) {
        GregorianCalendar aCalendar = new GregorianCalendar();
        if (time != null) {
            aCalendar.setTimeInMillis(time.getTime());
        }
        return aCalendar;
    }

    /*
     * 取本周7天的第一天（周一的日期）
     */
    public static String getNowWeekBegin() {
        int mondayPlus;
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1;// 因为按中国礼拜一作为第一天所以这里减1
        if (dayOfWeek == 1) {
            mondayPlus = 0;
        } else {
            mondayPlus = 1 - dayOfWeek;
        }
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus);
        Date monday = currentDate.getTime();
        String preMonday = getFormattedDateTime(monday);
        return preMonday;
    }

    // 获取日期星期几
    public static int dayForWeek(String pTime) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(pTime));
        int dayForWeek = 0;
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            dayForWeek = 7;
        } else {
            dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return dayForWeek;
    }

    /**
     * 获得指定日期的前一天
     *
     * @param specifiedDay
     * @return
     * @throws Exception
     */
    public static String getSpecifiedDayBefore(String specifiedDay) {
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day - 1);

        String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return dayBefore;
    }

    /**
     * 获得指定日期的后一天
     *
     * @param specifiedDay
     * @return
     */
    public static String getSpecifiedDayAfter(String specifiedDay) {
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day + 1);

        String dayAfter = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return dayAfter;
    }

    public static String getDayOfMonthWith1() {
        SimpleDateFormat format = new SimpleDateFormat("MM.dd");
        // 获取当前月第一天：
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
        String first = format.format(c.getTime());
        return first;
    }

    public static String getNowString() {
        // 设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("MM.dd");
        String nowStr = df.format(new Date());
        return nowStr;
    }

    //将字符串日期转成毫秒
    public static long dataTurntoLong(String date) {
        //去除-
        String dateStr0 = date.replace(" ", "-");
        String dateStr = dateStr0.trim().replaceAll("-", "");
        String dateTime = dateStr.trim().replaceAll(":", "");
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(new SimpleDateFormat("yyyyMMddHHmmss").parse(dateTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println("时间转化后的毫秒数为：" + c.getTimeInMillis());
        return c.getTimeInMillis();
    }



    public static long getDateLongTime(Date date, String format) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String strDate = sdf.format(date);
        Date newDate = sdf.parse(strDate);
        return newDate.getTime();
    }

    public static Timestamp redOneSecond(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.SECOND, -1);
        return new Timestamp(calendar.getTime().getTime());
    }

    public static Timestamp date2Timestamp(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return new Timestamp(calendar.getTime().getTime());
    }

    public static void maixn(String[] args) throws Exception {
        Date now = getCalendarCurrentTimestamp();
        Date end = new Timestamp(now.getTime() + 3L * 30 * 24 * 60 * 60 * 1000 + 5L * 24 * 60 * 60 * 1000);
        System.out.println(betweenMonthByTime(now, end));
    }


    public static final long ONE_MINUTE_MILLIONS = 60 * 1000;
    public static final long ONE_HOUR_MILLIONS = 60 * ONE_MINUTE_MILLIONS;
    public static final long ONE_DAY_MILLIONS = 24 * ONE_HOUR_MILLIONS;

    public static String getTimeElapse(Date date) {
        String str = "";

        try {
            Date curDate = new Date();

            long durTime = curDate.getTime() - date.getTime();
            int dayStatus = calculateDayStatus(date, curDate);

            if (durTime <= 10 * ONE_MINUTE_MILLIONS) {
                str = "刚刚";
            } else if (durTime < ONE_HOUR_MILLIONS) {
                str = durTime / ONE_MINUTE_MILLIONS + "分钟前";
            } else if (dayStatus == 0) {
                str = durTime / ONE_HOUR_MILLIONS + "小时前";
            } else if (dayStatus == -1) {
                str = "昨天" + new SimpleDateFormat("HH:mm").format(date);
            } else if (isSameYear(date, curDate) && dayStatus < -1) {
                str = new SimpleDateFormat("MM-dd").format( date);
            } else {
                str = new SimpleDateFormat("yyyy-MM-dd").format( date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static boolean isSameYear(Date targetTime, Date compareTime) {
        Calendar tarCalendar = Calendar.getInstance();
        tarCalendar.setTime(targetTime);
        int tarYear = tarCalendar.get(Calendar.YEAR);

        Calendar compareCalendar = Calendar.getInstance();
        compareCalendar.setTime(compareTime);
        int comYear = compareCalendar.get(Calendar.YEAR);

        return tarYear == comYear;
    }

    public static int calculateDayStatus(Date targetTime, Date compareTime) {
        Calendar tarCalendar = Calendar.getInstance();
        tarCalendar.setTime(targetTime);
        int tarDayOfYear = tarCalendar.get(Calendar.DAY_OF_YEAR);

        Calendar compareCalendar = Calendar.getInstance();
        compareCalendar.setTime(compareTime);
        int comDayOfYear = compareCalendar.get(Calendar.DAY_OF_YEAR);

        return tarDayOfYear - comDayOfYear;
    }

    public static Timestamp todayStart(){
        SimpleDateFormat formatDay = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Timestamp curday = getCalendarCurrentTimestamp();
        String dayStr = formatDay.format(curday.getTime());
        Timestamp ts = Timestamp.valueOf(dayStr);
        return ts;
    }

    public static Timestamp todayStart(Timestamp curday){
        SimpleDateFormat formatDay = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        //Timestamp curday = getCalendarCurrentTimestamp();
        String dayStr = formatDay.format(curday.getTime());
        Timestamp ts = Timestamp.valueOf(dayStr);
        return ts;
    }

    public static Timestamp todayEnd(Timestamp curday){
        SimpleDateFormat formatDay = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
        //Timestamp curday = getCalendarCurrentTimestamp();
        String dayStr = formatDay.format(curday.getTime());
        Timestamp ts = Timestamp.valueOf(dayStr);
        return ts;
    }

    public static boolean compare_date(String date1, String date2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dt1 = df.parse(date1);
            Date dt2 = df.parse(date2);
            if (dt1.getTime() > dt2.getTime()) {
                return true;
            } else if (dt1.getTime() < dt2.getTime()) {
                return false;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return false;
    }

    /**
     * 获取指定时间毫秒数
     * @param time
     * @return
     */
    public static long getTimeMillis(String time){
        try {
            DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
            DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
            Date curDate = dateFormat.parse(dayFormat.format(new Date())+""+time);
            return curDate.getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取前月的第一天
     * @return
     */
    public static String getMonthFirstDay(){
        //获取前月的第一天
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH,1);
        String firstDay = format.format(cal.getTime());
        return firstDay;
    }

    /**
     * 获取前月最后一天
     * @return
     */
    public static String getMonthLastDay(){
        //获取前月的最后一天
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 1);
        cal.set(Calendar.DAY_OF_MONTH,1);
        String lastDay = format.format(cal.getTime());
        return lastDay;
    }

    /**
     * 某年某月的第一天
     * @param year
     * @param month
     * @return
     */
    public static String getFirstDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month-1);
        cal.set(Calendar.DAY_OF_MONTH,cal.getMinimum(Calendar.DATE));
        return   new   SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime());
    }

    /**
     * 某年某月的最后一天
     * @param year
     * @param month
     * @return
     */
    public static String getLastDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month-1);
        cal.set(Calendar.DAY_OF_MONTH,cal.getActualMaximum(Calendar.DATE));
        return new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime());
    }

    public static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 字符串转换成日期
     * @param str
     * @return date
     */
    public static Date StrToDate(String str) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static boolean checkAfterDay(String str) {
        boolean flag = false;
        try {
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            Date d = format.parse(str);
            flag = d.before(date);
            if (flag) {
                flag = true;
            } else {
                flag = false;
            }
        }catch (ParseException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 
    * @Title: getTimeInterval 
    * @Description: 获取当前一周7天日期
    * @param
    * @return List<String>
    * @throws
     */
    public static List<String> getTimeInterval() { 
    	List<String> list = new ArrayList<String>();
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        Calendar c = Calendar.getInstance();  
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK );
        
        if (c.getFirstDayOfWeek() == Calendar.SUNDAY) {
            c.add(Calendar.DAY_OF_MONTH, 1);
        }
        // 计算一周开始的日期
        c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
         
        for (int i=1;i<=7;i++) {
            c.add(Calendar.DAY_OF_MONTH, 1);
            list.add(sdf.format(c.getTime()));
        }
        return list;
   }
    /**
     * 返回两个日期之间隔了多少分钟
     * @param Date1
     * @param date2
     * @return
     * @throws Exception
     */
    public static long minDiff(Date Date1, Date date2) {  
        return Math.abs((Date1.getTime()-date2.getTime())/(1000*60));
    }

    /**
     * 返回两个时间戳隔了多少分钟
     * @param time1
     * @param time2
     * @return
     */
    public static long minDiff(long time1,long time2) {
        return Math.abs((time1-time2)/(1000*60));
    }

    /**
     * 返回两个日期之间隔了多少分钟
     * @param Date1
     * @param date2
     * @return
     * @throws Exception
     */
    public static long secondDiff(Date Date1, Date date2) {  
        return Math.abs((Date1.getTime()-date2.getTime())/(1000));
    }

    /**
     * 返回两个时间戳之间隔了多少分钟
     * @param time1
     * @param time2
     * @return
     * @throws Exception
     */
    public static long secondDiff(long time1, long time2) {
        return Math.abs((time1-time2)/(1000));
    }


    /**
     * 获取日期初始
     */
    public static Date getDateStart(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
    /**
     * 获取日期结束
     */
    public static Date getDateEnd(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
    
    /**
     * 
    * @Title: isBelong 
    * @Description: 当前时间HH:mm  和时间段比较
    * @return 
    * @throws
     */
    public static boolean isBelong(Date now, String beginTime, String endTime){
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
        Date bTime = null;
        Date eTime = null;
        try {
            now = df.parse(df.format(now));
            bTime = df.parse(beginTime);
            eTime = df.parse(endTime);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return now.before(bTime) && now.after(eTime);
    }
    /**
     *
     * @Title: isBelong
     * @Description: 当前时间HH:mm  和时间段比较
     * @param flag 1:是否时间段之间;2:是否时间段之前;3:是否时间段之后
     * @return
     * @throws
     */
    public static boolean isBelong(Date now,String beginTime, String endTime, int flag){
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
        Date bTime = null;
        Date eTime = null;
        try {
            now = df.parse(df.format(now));
            bTime = df.parse(beginTime);
            eTime = df.parse(endTime);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return belongCalendar(now, bTime, eTime, flag);
    }

    /**
     * 判断时间与时间段比较
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime, int flag) {
        boolean result = false;
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (flag == 1 && date.compareTo(begin) > -1 && date.compareTo(end) < 1) {
            result = true;
        } else if (flag == 2 && date.compareTo(begin) < 1) {
            result = true;
        } else if (flag == 3 && date.compareTo(end) > -1) {
            result = true;
        }
        return result;
    }


    public static boolean isToday(long time) {
        boolean isToday = false;
        try {
            long cdayTime = DateUtil.getCalendarCurrentTimeInMillis();
            if (time > cdayTime - 24*60*60*1000) {
                isToday = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isToday;
    }

    public static long getBeaconTime(String date) {
        date = date.replace("T", " ").replace("Z", "");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.util.Date utilDate = null;
        try {
            utilDate = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return utilDate.getTime()/1000l;
    }

    public static void main(String[]args) {
        long time = 1532627999*1000l;
        System.out.println(DateUtil.getTimestatmpByTime(time));
        System.out.println(time);
        System.out.println(isToday(time));
        //System.out.println(addHour(getDateByString(getCurrDate()),0));
        //System.out.println(addHour(getDateByString(getCurrDate()),1));
    }
}
